<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs页 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="catelist"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单item的item项 -->
            <el-form-item :label="item.attr_name" v-for="item in manyTabData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="cb" v-for="(cb,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyTabData" :label="item.attr_name" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
              :headers="headers"
            >
              <!-- 为什么之前axios中加拦截器的时候已经配置过headers 了, 现在为什么还要手动配置, 原因: 该组件自定义发送 -->
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce" />
            <el-button type="primary" size="mini" @click="add">添加商品</el-button>
          </el-tab-pane>
          <el-tab-pane label="完成" name="5">完成</el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" class="preview-img" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  created() {
    this.__getCateList()
  },
  data() {
    return {
      activeIndex: '0',
      // 添加参数对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品分类数组
        goods_cat: [],
        // 图片的数组
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 验证表单规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      catelist: [],
      // 级联对象
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      manyTabData: [], // 动态参数
      onlyTabData: [], // 静态属性
      // 上传图片的服务器地址
      // http://127.0.0.1:8888/api/private/v1/uplaod
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览tu片地址
      previewPath: '',
      previewVisible: false
    }
  },
  methods: {
    // ------------- 发送请求 -------------
    async __getCateList() {
      const { data: res } = await this.$http.get('categories')

      if (res.meta.status !== 200) {
        return this.$showToast.error('获取分类数据失败')
      }
      this.catelist = res.data
    },
    // ---------- 事件监听 ------------
    // 级联选择器数据发生变化
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
        return false
      }
    },
    // tab页发生变化时, 当值为return false时, 阻止tab页跳转
    beforeTabLeave(newActiveName, oldActiveName) {
      console.log(newActiveName, oldActiveName)
      if (+oldActiveName === 0 && this.addForm.goods_cat.length !== 3) {
        this.$showToast.error('请选择商品分类')
        return false
      }
    },
    // 点击商品参数获取数据
    async tabClicked() {
      // 当 this.activeIndex = 1时, 点击的是商品参数many
      // 当 this.activeIndex = 2时, 点击的是商品属性 only
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )

        if (res.meta.status !== 200) {
          return this.$showToast.error('获取商品参数失败')
        }
        res.data.forEach(el => {
          el.attr_vals =
            el.attr_vals.length === 0 ? [] : el.attr_vals.split(' ')
        })
        this.manyTabData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )

        if (res.meta.status !== 200) {
          return this.$showToast.error('获取商品参数失败')
        }
        // res.data.forEach(el => {
        //   el.attr_vals =
        //     el.attr_vals.length === 0 ? [] : el.attr_vals.split(' ')
        // })
        this.onlyTabData = res.data
      }
    },
    // 点击图片预览
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    // 点击移除图片
    handleRemove(file) {
      const picsPath = file.response.data.tmp_path
      console.log(picsPath)
      this.addForm.pics = this.addForm.pics.filter(el => el.pics !== picsPath)
      console.log(this.addForm.pics)
    },
    // 图片上传成功
    handleSuccess(response) {
      console.log(response)
      if (response.meta.status !== 200) {
        return this.$showToast.error('上传失败')
      }
      this.$showToast.success('上传成功')
      this.addForm.pics.push({ pics: response.data.tmp_path })
      console.log(this.addForm.pics)
    },
    // 添加商品
    add() {
      // 1先验证表单是否通过
      this.$refs.addFormRef.validate(async vaild => {
        if (!vaild) {
          return this.$showToast.error('请填写必要的选项')
        }
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')

        // 动态参数
        this.manyTabData.forEach(el => {
          const o = {
            attr_id: el.attr_id,
            attr_value: el.attr_vals.join(' ')
          }
          this.addForm.attrs.push(o)
        })
        // 静态属性
        this.onlyTabData.forEach(el => {
          const o = {
            attr_id: el.attr_id,
            attr_value: el.attr_vals
          }
          this.addForm.attrs.push(o)
        })
        form.attrs = this.addForm.attrs

        // 添加商品
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) {
          return this.$showToast.error('添加商品失败')
        }
        this.$showToast.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId() {
      return this.addForm.goods_cat.length === 3
        ? this.addForm.goods_cat[2]
        : null
    }
  }
}
</script>

<style lang='less' scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.preview-img {
  width: 100%;
}

.el-button {
  margin-top: 15px;
}
</style>
